import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import { useUserStore } from '@/stores/user'
import { checkSuperAdmin } from '@/utils/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/Home.vue'),
      meta: { requiresAuth: true },
    }, 
    {
      path: '/login',
      name: 'login',
      component: Login,
      beforeEnter: (to, from, next) => {
        const userStore = useUserStore();
        if (userStore.isLoggedIn) {
          userStore.logout(); // 退出登录状态
        }
        next();
      }
    },
    {
      path: '/personal',
      name: 'personal',
      component: () => import('@/views/Personal.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/goods',
      name: 'goods',
      component: ()=>import('@/views/Goods.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/purchase',
      name: 'purchase',
      component: () => import('@/views/Purchase.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/sales',
      name: 'sales',
      component: ()=>import('@/views/Sales.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/stock',
      name: 'stock',
      component: () => import('@/views/Stock.vue'),
      meta: { requiresAuth: true },
    },
  ],
})

// 动态添加 /employee 路由
function addEmployeeRoute() {
  router.addRoute({
    path: '/employee',
    name: 'employee',
    component: () => import('@/views/Employee.vue'),
    meta: { requiresAuth: true }
  });
}

// 在退出登录时移除 /employee 路由
function removeEmployeeRoute() {
  router.removeRoute('employee');
}

router.beforeEach(async (to,from,next)=>{
  //登陆状态
  const userStore = useUserStore()
  const storedStatus = localStorage.getItem('isLoggedIn');
  userStore.isLoggedIn = storedStatus === 'true';
  // 判断 token 是否有效
  const token = localStorage.getItem('token');
  const isTokenValid = token && userStore.checkTokenExpiration();

  //判断是否需要登录
  if(to.meta.requiresAuth && ( !userStore.isLoggedIn || !isTokenValid)){
    userStore.redirectPath = to.fullPath;
    next({path:'/login',query:{redirect:to.fullPath}})
  }
  // 如果已经登录，验证权限并动态添加/移除 /employee 路由
  if (token) {
    userStore.isSuperAdmin = await checkSuperAdmin()
    if (userStore.isSuperAdmin) {
      if (!router.hasRoute('employee')) {
        addEmployeeRoute();
      }
    } else {
      if (router.hasRoute('employee')) {
        removeEmployeeRoute();
      }
    }
  }
  next();
})

export default router;
